package com.lxmes.gs.service.impl;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.lxmes.gs.domain.*;
import com.lxmes.gs.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.lxmes.common.utils.StringUtils;
import com.lxmes.common.utils.bean.BeanValidators;
import com.lxmes.common.exception.ServiceException;
import javax.validation.Validator;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lxmes.gs.mapper.ProjectApprovalMapper;
import org.springframework.transaction.annotation.Transactional;

/**
 * 项目立项Service业务层处理
 * 
 * @author wdf
 * @date 2023-04-24
 */
@Service
public class ProjectApprovalServiceImpl extends ServiceImpl<ProjectApprovalMapper,ProjectApproval> implements IProjectApprovalService{
    
    @Autowired
    private ProjectApprovalMapper projectApprovalMapper;
    @Autowired
    protected Validator validator;
    @Autowired
    private IIssuedProjectsService issuedProjectsService;
    @Autowired
    private IProjectStatisticsService projectStatisticsService;
    @Autowired
    private IProjectOrganizationService projectOrganizationService;
    @Autowired
    private IProjectStaffService projectStaffService;
    /**
     * 查询项目立项
     * 
     * @param id 项目立项主键
     * @return 项目立项
     */
    @Override
    public ProjectApproval selectProjectApprovalById(Long id){
        return projectApprovalMapper.selectById(id);
    }

    /**
     * 查询项目立项列表
     * 
     * @param projectApproval 项目立项
     * @return 项目立项
     */
    @Override
    public List<ProjectApproval> selectProjectApprovalList(ProjectApproval projectApproval){
        return projectApprovalMapper.selectList(Wrappers.lambdaQuery(projectApproval));
    }

    /**
     * 新增项目立项
     * 
     * @param projectApproval 项目立项
     * @return 结果
     */
    @Override
    public int insertProjectApproval(ProjectApproval projectApproval){
        String approvalCode = StrUtil.format("XM{}{}" , DateUtil.format(new Date(), "yyyyMMdd"), NumberUtil.decimalFormat("000" , RandomUtil.randomInt(1, 1000)));
        projectApproval.setApprovalCode(approvalCode);
        setName(projectApproval);
        return projectApprovalMapper.insert(projectApproval);
    }

    private void setName(ProjectApproval projectApproval) {
        ProjectOrganization one = projectOrganizationService.getOne(Wrappers.lambdaQuery(ProjectOrganization.class).eq(ProjectOrganization::getDepartmentCode, projectApproval.getInitiateUnitCode()));
        projectApproval.setInitiateUnit(one.getDepartmentName());
        ProjectOrganization one1 = projectOrganizationService.getOne(Wrappers.lambdaQuery(ProjectOrganization.class).eq(ProjectOrganization::getDepartmentCode, projectApproval.getResponsibleUnitCode()));
        projectApproval.setResponsibleUnit(one1.getDepartmentName());

        ProjectStaff one2 = projectStaffService.getOne(Wrappers.lambdaQuery(ProjectStaff.class).eq(ProjectStaff::getEmployeeId, projectApproval.getInitiatorPersonCode()));
        projectApproval.setInitiatorPerson(one2.getName());
        ProjectStaff one3 = projectStaffService.getOne(Wrappers.lambdaQuery(ProjectStaff.class).eq(ProjectStaff::getEmployeeId, projectApproval.getResponsiblePersonCode()));
        projectApproval.setResponsiblePerson(one3.getName());
    }

    /**
     * 修改项目立项
     * 
     * @param projectApproval 项目立项
     * @return 结果
     */
    @Override
    public int updateProjectApproval(ProjectApproval projectApproval){
        setName(projectApproval);
        return projectApprovalMapper.updateById(projectApproval);
    }

    /**
     * 批量删除项目立项
     * 
     * @param ids 需要删除的项目立项主键
     * @return 结果
     */
    @Override
    public int deleteProjectApprovalByIds(Long[] ids){
        return projectApprovalMapper.deleteProjectApprovalByIds(ids);
    }

    /**
     * 删除项目立项信息
     * 
     * @param id 项目立项主键
     * @return 结果
     */
    @Override
    public int deleteProjectApprovalById(Long id){
        return projectApprovalMapper.deleteById(id);
    }
    @Override
    public String imporIteminfo(List<ProjectApproval> projectApprovalList, boolean updateSupport) {
        if (StringUtils.isNull(projectApprovalList) || projectApprovalList.size() == 0)
        {
            throw new ServiceException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (ProjectApproval projectApproval : projectApprovalList)
        {
            try
            {
                BeanValidators.validateWithException(validator, projectApproval);
                this.insertProjectApproval(projectApproval);
                successNum++;
                successMsg.append("<br/>" + successNum + "数据导入成功");
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/> 数据导入失败：";
                failureMsg.append(msg + e.getMessage());
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int auditProjectApproval(Long[] ids) {
        List<ProjectApproval> projectApprovals = baseMapper.selectBatchIds(Arrays.asList(ids));
        boolean alreadyAudit = projectApprovals.stream().anyMatch(i -> StrUtil.equals(i.getAuditDown(), "1"));
        if (alreadyAudit) {
            throw new ServiceException("存在已审核数据,操作失败");
        }
        for (ProjectApproval projectApproval : projectApprovals) {
            projectApproval.setAuditDown("1");
            baseMapper.updateById(projectApproval);
            
            IssuedProjects issuedProjects = BeanUtil.copyProperties(projectApproval, IssuedProjects.class);
            issuedProjects.setPlanStatus("2");
            issuedProjects.setIssueTime(new Date());
            issuedProjectsService.insertIssuedProjects(issuedProjects);
            
            ProjectStatistics projectStatistics = BeanUtil.copyProperties(projectApproval, ProjectStatistics.class);
            projectStatisticsService.insertProjectStatistics(projectStatistics);
        }
        return 1;
    }
}
